from django.shortcuts import render, redirect, HttpResponse
from django.forms import Form, fields, widgets
from rbac import models
from django.conf import settings
from rbac.service.init_permission import initial_permission

# Create your views here.

class LoginForm(Form):
    """
    登陆表单
    """
    username = fields.CharField(required=True, error_messages={"required":"用户名不能为空"},
                                widget=widgets.TextInput(attrs={"class":"form-control","id":"inputEmail3"}))
    password = fields.CharField(required=True, error_messages={"required":"密码不能为空"},
                                widget=widgets.PasswordInput(
                                    attrs={"class":"form-control","id":"inputEmail3"}
                                ))


def login(request):
    '''
    登陆
    :param request: 
    :return: 
    '''
    if request.method == "GET":
        form = LoginForm()
        return render(request, "app01/login.html", {"form":form})
    elif request.method == "POST":
        form = LoginForm(data=request.POST)
        if form.is_valid():
            user = models.UserInfo.objects.filter(**form.cleaned_data).first()
            if user:
                initial_permission(request, user)
                request.session['UserName'] = user.username
                request.session['Uid'] = user.id
                return render(request, 'app01/index.html')
            else:
                # 登录失败，主动提示错误
                # form.add_error("password", "用户名或密码错误")
                from django.core.exceptions import ValidationError
                form.add_error("password", ValidationError('用户名或密码错误'))
        return render(request, 'app01/login.html', {'form': form})

def index(request):
    '''
    首页
    :param request: 
    :return: 
    '''
    return render(request, 'app01/index.html')
